/**
 * chrome相关api - TypeScript 版本
 * @author rambler
 * @date 2023年2月9日09:42:35
 */
import {getRandomInt} from "@/utils/random.ts";

// 书签节点类型（可复用 Chrome 内置定义）
type BookmarkTreeNode = chrome.bookmarks.BookmarkTreeNode;
type HistoryItem = chrome.history.HistoryItem;

/**
 * 获取书签树
 */
export function getBookmarkTree(): Promise<BookmarkTreeNode[]> {
    return new Promise((resolve) => {
        if (!chrome.bookmarks) {
            resolve([]);
            return;
        }
        chrome.bookmarks.getTree().then((res) => {
            // 默认情况下chrome书签分为书签栏和其他书签
            // 为了考虑到用户体验，将其他书签合并到书签栏中，作为一个独立的文件夹
            const result: BookmarkTreeNode[] = res[0].children?.[0]?.children || [];
            if (res[0].children?.[1]) {
                result.push(res[0].children[1]);
            }
            resolve(result);
        });
    });
}

/**
 * 获取 favicon 图标地址
 */
export function getIconUrl(url: string, size: number = 32): string {
    if (!chrome.runtime || !url) {
        return "";
    }
    const prepareUrl = new URL(chrome.runtime.getURL("/_favicon/"));
    prepareUrl.searchParams.set("pageUrl", url);
    prepareUrl.searchParams.set("size", size.toString());
    return prepareUrl.toString();
}

/**
 * 创建书签收藏夹
 */
export function createBookmarkFolder(title: string, parentId: string = "0"): void {
    if (!chrome.bookmarks) {
        throw new Error("无法访问chrome api");
    }
    chrome.bookmarks.create({
        parentId,
        title,
    });
}

/**
 * 获取书签子树
 */
export function getBookmarkSubTree(id: string): Promise<BookmarkTreeNode[]> {
    return new Promise((resolve) => {
        if (!chrome.bookmarks) {
            resolve(randomData());
            return;
        }
        chrome.bookmarks.getChildren(id, (list) => {
            resolve(list);
        });
    });
}

/**
 * 更新书签
 */
export function updateBookmark(
    id: string,
    title: string,
    url: string
): Promise<BookmarkTreeNode> {
    if (!chrome.bookmarks) {
        throw new Error("无法访问chrome对象");
    }
    return new Promise((resolve, reject) => {
        try {
            chrome.bookmarks.update(id, { title, url }, (result) => {
                if (result) {
                    resolve(result);
                } else {
                    reject("更新失败");
                }
            });
        } catch (e) {
            reject("更新书签异常");
        }
    });
}

/**
 * 删除书签
 */
export function removeBookmark(id: string): Promise<void> {
    if (!chrome.bookmarks) {
        throw new Error("无法访问chrome对象");
    }
    return new Promise((resolve, reject) => {
        if (!id) {
            reject("id为空，删除失败");
            return;
        }
        chrome.bookmarks.remove(id, () => {
            resolve();
        });
    });
}

/**
 * 删除书签文件夹
 */
export function removeBookmarkTree(bookmarkTreeId: string): Promise<void> {
    if (!chrome.bookmarks) {
        throw new Error("无法访问chrome对象");
    }
    return new Promise((resolve, reject) => {
        if (!bookmarkTreeId) {
            reject("文件夹id为空，删除失败");
            return;
        }
        chrome.bookmarks.removeTree(bookmarkTreeId, () => {
            resolve();
        });
    });
}

/**
 * 在 chrome 历史记录中搜索
 */
export function searchFromHistory(
    keywords: string,
    total: number
): Promise<(HistoryItem & { from: string; tag: string })[]> {
    return new Promise((resolve) => {
        if (!chrome.history || !keywords) {
            resolve([]);
            return;
        }
        chrome.history.search(
            {
                text: keywords,
                maxResults: total,
            },
            (res) => {
                resolve(
                    res.map((ele) => ({
                        ...ele,
                        from: "history",
                        tag: "历史",
                    }))
                );
            }
        );
    });
}

/**
 * mock bookmark data
 */
const randomData = (): BookmarkTreeNode[] => {
    const arr: BookmarkTreeNode[] = [];
    const times = getRandomInt(2, 10);
    for (let i = 0; i < times; i++) {
        arr.push({
            dateAdded: Date.now(),
            id: i.toString(),
            index: i,
            parentId: "0",
            title: "随机" + i,
            url: i % 2 === 0 ? "https://example.com" : undefined,
        });
    }
    return arr;
};

export default {
    getBookmarkTree,
    getIconUrl,
    createBookmarkFolder,
    getBookmarkSubTree,
    updateBookmark,
    removeBookmark,
    removeBookmarkTree,
    searchFromHistory,
    randomData,
}